package fm.dongman.animefm.view.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.flexbox.FlexboxLayout;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import fm.dongman.animefm.R;
import fm.dongman.animefm.contractlib.contract.SearchContract;
import fm.dongman.animefm.view.activity.SingleActivity;
import fm.dongman.animefm.view.util.ActivityHelper;
import fm.dongman.animefm.view.util.ToastHelper;
import fm.dongman.modellib.StaticArea.Injection;
import fm.dongman.presenterlib.presenter.SearchPresenter;

import static fm.dongman.animefm.view.activity.SingleActivity.Companion;

/**
 * @author alex 2017.10.18
 * @description 搜索页面
 */
public class SearchFragment extends BaseFragment implements View.OnClickListener, SearchContract.ISearchView {

    private TextView mInputTexView;
    private ImageButton mIbBack;
    private ImageButton mIbSearchBtn;
    private TextView mTvClearHistory;
    private String mCurKeyWords;
    private FlexboxLayout mFlexHotRecommendLayout;
    private SearchContract.ISearchPresenter iSearchPresenter;
    private FlexboxLayout mFlexHistoryLayout;


    public SearchFragment() {
    }


    /**
     * @return SearchFragment 的实例
     */
    public static SearchFragment newInstance() {
        SearchFragment fragment = new SearchFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View layoutView = inflater.inflate(R.layout.fragment_search, container, false);
        initComponents(layoutView);
        return layoutView;
    }

    /**
     * 初始化组件
     *
     * @param layoutView
     */
    private void initComponents(View layoutView) {
        mInputTexView = (EditText) layoutView.findViewById(R.id.mActSearchInput);
        mIbBack = (ImageButton) layoutView.findViewById(R.id.mIbSearchBack);
        mIbSearchBtn = (ImageButton) layoutView.findViewById(R.id.mIbSearchBtn);
        mFlexHotRecommendLayout = (FlexboxLayout) layoutView.findViewById(R.id.mFbSearchRecommendBox);
        mFlexHistoryLayout = (FlexboxLayout) layoutView.findViewById(R.id.mFbSearchHistoryBox);
        mTvClearHistory = (TextView) layoutView.findViewById(R.id.mTvSearchClearHistory);

        mIbSearchBtn.setOnClickListener(this);
        mIbBack.setOnClickListener(this);
        mTvClearHistory.setOnClickListener(this);

        mInputTexView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                doSearch();
                return true;
            }
        });
    }

    /**
     * 隐藏输入法
     */
    private void hideInputMethod() {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(mInputTexView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void initData() {
        new SearchPresenter(this, Injection.provideSearchRepository(getActivity()));
    }

    @Override
    public void bindData() {
        iSearchPresenter.startLoad();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mIbSearchBtn:
                doSearch();
                break;
            case R.id.mIbSearchBack:
                hideInputMethod();
                ActivityHelper.INSTANCE.backActivity(getActivity());
                break;
            //清除历史记录
            case R.id.mTvSearchClearHistory:
                iSearchPresenter.clearHistorySearch();
                break;
        }

        if (v.getTag() != null) {
            if ((int) v.getTag() == 123) {
                String input = ((TextView) v).getText().toString();
                mInputTexView.setText(input);
                Intent intent = new Intent(getActivity(), SingleActivity.class);
                intent.putExtra(Companion.getEXTRA_NAME(), Companion.getINTENT_EXTRA_SEARCH_RESULT());
                intent.putExtra(Companion.getBUNDLE_EXTRA_KEY_ID(), input);
                ActivityHelper.INSTANCE.startActivity(getActivity(), intent);
            }
        }
    }

    public void doSearch() {
        if (mInputTexView.getText() == null || mInputTexView.getText().length() == 0) {
            ToastHelper.getInstance(getActivity()).showWarn("输入不能为空");
        } else {
            Intent intent = new Intent(getActivity(), SingleActivity.class);
            intent.putExtra(Companion.getEXTRA_NAME(), Companion.getINTENT_EXTRA_SEARCH_RESULT());
            intent.putExtra(Companion.getBUNDLE_EXTRA_KEY_ID(), mInputTexView.getText().toString());
            ActivityHelper.INSTANCE.startActivity(getActivity(), intent);
        }
    }

    @Override
    public void showHistorySearch(@NotNull List<String> historyList) {
        for (int i = 0; i < historyList.size(); i++) {
            LinearLayout linearLayout = (LinearLayout) View.inflate(getActivity(), R.layout.item_search_recommend_tips, null);
            TextView tv = (TextView) linearLayout.getChildAt(0);
            tv.setText(historyList.get(i));
            tv.setTag(123);
            tv.setOnClickListener(this);
            mFlexHistoryLayout.addView(linearLayout);
        }
    }

    @Override
    public void showHotSearch(@NotNull List<String> hotList) {
        for (int i = 0; i < hotList.size(); i++) {
            LinearLayout linearLayout = (LinearLayout) View.inflate(getActivity(), R.layout.item_search_recommend_tips, null);
            TextView tv = (TextView) linearLayout.getChildAt(0);
            tv.setText(hotList.get(i));
            tv.setTag(123);
            tv.setOnClickListener(this);
            mFlexHotRecommendLayout.addView(linearLayout);
        }
    }

    @Override
    public void setPresenter(SearchContract.ISearchPresenter presenter) {
        iSearchPresenter = presenter;
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @NotNull
    @Override
    public Context getViewContext() {
        return getActivity();
    }

    @Override
    public void showNoNetwork() {

    }

    @Override
    public void showRefreshFailed() {

    }

    @Override
    public void showClearHistoryState(boolean b) {
        if(b){
            ToastHelper.getInstance(getActivity()).showWarn("清除历史记录成功");
            mFlexHistoryLayout.removeAllViews();

        }else{
            ToastHelper.getInstance(getActivity()).showWarn("清除历史记录失败");
        }

    }
}
